import pymysql

class Model:
	
	tab_name = None
	link = None
	cursor = None
	pk = 'id'
	fields = ['cid','pwd','money']

	def __init__(self,table):
		try:
			self.tab_name = table
			self.link = pymysql.connect(host='localhost',user='root',password='123456',db="mydemo",port=3306,charset="utf8")
			self.cursor = self.link.cursor(pymysql.cursors.DictCursor)
		except Exception as err:
			print("SQL连接错误，错误原因是：%s"%(err))

	def __del__(self):
		#关闭连接对象和游标对象
		if self.cursor != None:
			self.cursor.close()
		if self.link != None:
			self.link.close()

	def findPWDByCID(self,id):
		try:
			sql = "select * from %s where %s='%s'"%(self.tab_name,'cid',id)
			print(sql)
			self.cursor.execute(sql)
			return self.cursor.fetchone()
		except Exception as err:
			print("SQL连接错误，错误原因是：%s"%(err))
			return None

	def save(self,data={}):
		try:
			values=[]
			for k,v in data.items():
				if (k in self.fields) and k != self.pk:
					values.append("%s='%s'"%(k,v))
			sql = "update %s set %s where %s='%s'"%(self.tab_name,','.join(values),self.pk,data.get(self.pk))
			print(sql)
			self.cursor.execute(sql)
			self.link.commit()
			#返回影响行数
			return self.cursor.rowcount
		except Exception as err:
			print("SQL连接错误，错误原因是：%s"%(err))
			return 

	def __loadFields(self):
		sql = "SHOW COLUMNS FROM %s"%(self.tab_name)
		self.cursor.execute(sql)
		dlist = self.cursor.fetchall()
		for v in dlist:
			self.fields.append(v['Field'])
			if v['key'] == 'PKI':
				self.pk = v['Field']
